package com.hdl.sqlSession;

import com.hdl.pojo.Configuration;
import com.hdl.pojo.MappedStatement;
import com.hdl.pojo.SqlType;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @author hedonglin
 * @date 2020/4/21 21:36
 * @description
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    private Executor executor = new SimpleExecutor();
    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> list = executor.query(configuration, mappedStatement, params);
        return list;
    }

    @Override
    public <E> E selectOne(String statementId, Object... params) throws IllegalAccessException, ClassNotFoundException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        List<E> list = selectList(statementId, params);

        if (list.size() == 0){
            return null;
        }else if (list.size() == 1){
            return list.get(0);
        }else {
            throw new RuntimeException("返回结果过多");
        }
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        return executor.update(configuration, mappedStatement, params);
    }

    @Override
    public int delete(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }

    @Override
    public <T> T getMapper(Class<T> mapperClass) {
        // 使用jdk动态代理为dao生成代理对象，并返回
        Object o = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 参数1准备，statementid
                String methodName = method.getName();
                String statementid = String.join(".", mapperClass.getName(), methodName);
                Object result;
                final SqlType sqlType = configuration.getMappedStatementMap().get(statementid).getSqlType();
                switch (sqlType) {
                    case SELECT: {
                        // 参数2准备 Object... params
                        Type genericReturnType = method.getGenericReturnType();
                        // 判断是否实现泛型类型参数化
                        if (genericReturnType instanceof ParameterizedType) {
                            result = selectList(statementid, args);
                        } else {
                            result = selectOne(statementid, args);
                        }
                    }
                    break;
                    case INSERT: {
                        result = insert(statementid, args);
                    }
                    break;
                    case UPDATE: {
                        result = update(statementid, args);
                    }
                    break;
                    case DELETE: {
                        result = delete(statementid, args);
                    }
                    break;
                    default: {
                        return null;
                    }
                }
                return result;
            }
        });
        return (T)o;
    }
}
